<?php

/*
 * db_mysql.php
 *
 * database handler for mysql
 */

// read comments in db.php for explanation

class MySQL_DBConnector extends DBConnector {

    var $defaultPort = 3306;

    function MySQL_DBConnector() { self::__construct(); }
    function __construct() 
    {
    }

    function __destruct() 
    {
    }

    function connect( $host, $port, $dbname, $user, $password )
    {
        $port = (is_null($port)) ? $this->defaultPort : $port;
        $host = $host.':'.$port;

        $this->conn = mysql_connect( $host, $user, $password );
        if( !$this->conn )
        {
						$this->setLastError( mysql_error() );
            $this->conn = null;
            return false;
        }

        if( !@mysql_select_db( $dbname, $this->conn ) )
        {
            // return last error
            $this->setLastError( mysql_error($this->conn) );
						// but no error
        }

        return true;
    }

    function disconnect()
    {
        if( is_null($this->conn) )
            die( 'MySQL_DBConnector::disconnect: unable to disconnnect: not connected.' );

        @mysql_close( $this->conn );
        $this->conn = null;
        return true;
    }

		function useDatabase( $dbName )
		{
				if( !@mysql_select_db( $dbName, $this->conn ) )
				{
					$this->setLastError( mysql_error($this->conn) );
					return false;
				}
				return true;
		}

    function select( $sql )
    {
        $result = @mysql_query( $sql, $this->conn );

        if( !$result )
        {
            $this->setLastError( mysql_error($this->conn) );
            return false;
        }

        return new MySQL_DBResult( &$this, $result );
    }
    
    function execute( $sql )
    {
        if( !(@mysql_query( $sql, $this->conn )) )
        {
            $this->setLastError( mysql_error($this->conn) );
            return false;
        }
        return true;
    }

		function lastId( $table, $fieldname )
		{
			return mysql_insert_id();
		}	

    function escapeStr( $txt )
    {
        return @mysql_real_escape_string( $txt );
    }
}

class MySQL_DBResult extends DBResult {

    function DBResult( &$connector, $resultset ) { self::__construct( &$connector, $resultset ); }
    function __construct( &$connector, $resultset )
    {
        parent::__construct( &$connector, $resultset );
    }

    function getNext()
    {
        if( !($this->row = @mysql_fetch_array($this->resultSet, MYSQL_ASSOC)) )
        {
            $this->connector->setLastError( mysql_error($this->connector->conn) );
            return false;
        }

        return $this->row;
    }

    function rowCount()
    {
        return @mysql_num_rows( $this->resultSet );
    }

    function columnCount()
    {
        return @mysql_num_fields( $this->resultSet );
    }

}

?>
